//
//  UIView+AddTap.m
//  testPod
//
//  Created by zjtdmac2 on 16/2/26.
//  Copyright © 2016年 zjtdmac2. All rights reserved.
//

#import "UIView+AddTap.h"
#import <objc/runtime.h> 

static char oneKey;
static char doubleKey;
static char longKey;
@implementation UIView (AddTap)

-(void)addGestures:(GesturesState )GesturesState didClick:(void (^)())didClick
{
    switch (GesturesState) {
        case tapPress:
        {
            UITapGestureRecognizer * singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
            [self addGestureRecognizer:singleTap];
            //如果单击双击共存
            for (UITapGestureRecognizer * doubleTap in self.gestureRecognizers) {
                if ([doubleTap isKindOfClass:[UITapGestureRecognizer class]] && doubleTap.numberOfTapsRequired==2 ) {
                    [singleTap requireGestureRecognizerToFail:doubleTap];
                }
            }
            objc_setAssociatedObject(self, &oneKey,didClick, OBJC_ASSOCIATION_COPY_NONATOMIC);
            break;
        }
        case doubleTapPress:
        {
            UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
            [doubleTap setNumberOfTapsRequired:2];
            [self addGestureRecognizer:doubleTap];
            //如果单击双击共存
            for (UITapGestureRecognizer * tap in self.gestureRecognizers) {
                if ([tap isKindOfClass:[UITapGestureRecognizer class]] && tap.numberOfTapsRequired==1 ) {
                    [tap requireGestureRecognizerToFail:doubleTap];
                }
            }
            
            objc_setAssociatedObject(self, &doubleKey,didClick, OBJC_ASSOCIATION_COPY_NONATOMIC);
            break;
       }
            
        case longPress:
        {
            UILongPressGestureRecognizer * longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
            longPressGr.minimumPressDuration = 1.0;
            [self addGestureRecognizer:longPressGr];
            objc_setAssociatedObject(self, &longKey,didClick, OBJC_ASSOCIATION_COPY_NONATOMIC);
            break;
        }
            
        default:
            break;
    }
    self.userInteractionEnabled=YES;
}
-(void)singleTap:(UITapGestureRecognizer *)tap
{
    void (^block)() = (void (^)())objc_getAssociatedObject(self, &oneKey);
    if (block) {
        block();
    }
}
-(void)doubleTap:(UITapGestureRecognizer *)doubleTap
{
    void (^block)() = (void (^)())objc_getAssociatedObject(self, &doubleKey);
    if (block) {
        block();
    }
    
}
-(void)longPressToDo:(UILongPressGestureRecognizer *)longPress
{
    if (longPress.state == UIGestureRecognizerStateBegan ) {
        void (^block)() = (void (^)())objc_getAssociatedObject(self, &longKey);
        if (block) {
            block();
        }
    }
}


@end
